tic;

javaaddpath 'C:\Program Files\MATLAB\R2019b\java\mij.jar'


MIJ.start('C:\Users\Lab\Fiji.app')

%% run

clearvars -except fastparams
starttime = datetime('now');
main_base = "----"; % add directory


bname = "efast1";
nrun = 500;
fnames = strings(1,nrun);
for i=1:nrun
    fnames(i) = strcat(main_base, "/",bname, "_", string(i));
end

notes = "test timing";


p = [0.6 + (rand(1))*0.8, 1/5, 1/70, 0.8, 0.9, 15, 0, 1/5, 0.8, 10,0, 0.6, 0.8,nrun];

% use parameters above or iterate over parameter ranges to populate a
% matrix ps
ps = [];
for i=1:nrun %size(p,1)
    
    % example using efast parameters
    p = [fastparams(i,1), fastparams(i,2), 1/70, fastparams(i,3), fastparams(i,4), fastparams(i,5),...
        fastparams(i,6), fastparams(i,7), fastparams(i,8), 10,0, 0.6, 0.8,nrun];
    
    ps = horzcat(ps, p');
end


for k=1:nrun
    javaaddpath 'C:\Program Files\MATLAB\R2019b\java\mij.jar'
    javaaddpath 'C:\Program Files\MATLAB\R2019b\java\ij.jar'
    MIJ.start('C:\Users\Lab\Fiji.app')
    basedir = fnames(k);
    
    
    fid=fopen('C:\Users\Lab\Downloads\basefile.txt','wt');
    fprintf(fid, '%s', basedir');
    fclose(fid);
    
    fid=fopen('C:\Users\Lab\Downloads\params.txt','wt');
    fprintf(fid, '%f \n', ps(:,k)');
    fclose(fid);
    
    ps_now = ps(:,k);
    
    
    cd("------")
    
    
    if isfile(basedir)
        rmdir(basedir)
    else
        mkdir(basedir)
        mkdir(strcat(basedir, "/rois"));
    end
    
    
    MIJ.run("Install...", "install=[ext fast h1 one cell ijm file path]")
    MIJ.run("Run extone small")
    MIJ.run("Install...", "install=[/ext_fast_h2.ijm]")
    
    
    MIJ.run("Run extwo")
    
    
    prompt = "Continue? 1/0: ";
    answer = 1;
    
    
    if (answer==1)
        if exist('Corona', 'dir')
            rmdir Coronas s
        end
        
        
        MIJ.run("cellstrain new box")
        
    end
    
    MIJ.run("Clear Results");
    MIJ.closeAllWindows
    MIJ.exit
    javarmpath 'C:\Program Files\MATLAB\R2019b\java\mij.jar'
    javarmpath 'C:\Program Files\MATLAB\R2019b\java\ij.jar'
    
    % Import Cellstrain
    % Script for importing data from the following text file:
    %
    %
    %
    % Auto-generated by MATLAB on 05-Nov-2021 13:48:08
    opts = delimitedTextImportOptions("NumVariables", 10);
    
    % Specify range and delimiter
    opts.DataLines = [2, Inf];
    opts.Delimiter = "\t";
    
    % Specify column names and types
    opts.VariableNames = ["SliceNumA", "CellID", "CentroidX", "CentroidY", "Angle", "major", "minor", "Area", "Width", "Height"];
    opts.VariableTypes = ["double", "double", "double", "double", "double", "double", "double", "double", "double", "double"];
    
    % Specify file level properties
    opts.ExtraColumnsRule = "ignore";
    opts.EmptyLineRule = "read";
    
    % Import the data
    CellEllipse = readtable(strcat(basedir, "/CellEllipse.txt"), opts);
    
    
    % Clear temporary variables
    clear opts
    
    % Import CoronaData
    % Script for importing data from the following text file:
    %
    %    filename:
    %
    % Auto-generated by MATLAB on 05-Nov-2021 16:16:34
    
    % Setup the Import Options and import the data
    opts = delimitedTextImportOptions("NumVariables", 11);
    
    % Specify range and delimiter
    opts.DataLines = [2, Inf];
    opts.Delimiter = "\t";
    
    % Specify column names and types
    opts.VariableNames = ["CellID", "SliceNumA", "CoronaCells", "CentroidX", "CentroidY", "Angle", "major", "minor", "Width", "Height", "Area"];
    opts.VariableTypes = ["double", "double", "string", "double", "double", "double", "double", "double", "double", "double", "double"];
    
    % Specify file level properties
    opts.ExtraColumnsRule = "ignore";
    opts.EmptyLineRule = "read";
    
    % Specify variable properties
    opts = setvaropts(opts, "CoronaCells", "WhitespaceRule", "preserve");
    opts = setvaropts(opts, "CoronaCells", "EmptyFieldRule", "auto");
    
    % Import the data
    CoronaData = readtable(strcat(basedir, "\Coronas\CoronaData.txt"), opts);
    
    
    % Clear temporary variables
    clear opts
    
    % Strain analysis
    
    % set p = IDs of zapped cells to speed up if extrusion
    
    % Setup the Import Options and import the data
    opts = delimitedTextImportOptions("NumVariables", 1);
    
    % Specify range and delimiter
    opts.DataLines = [2, Inf];
    opts.Delimiter = ",";
    
    % Specify column names and types
    opts.VariableNames = "Value";
    opts.VariableTypes = "double";
    
    % Specify file level properties
    opts.ExtraColumnsRule = "ignore";
    opts.EmptyLineRule = "read";
    
    % Import the data
    zap = readtable(strcat(basedir, "/zap.txt"), opts);
    
    % Convert to output type
    zap = table2array(zap);
    
    % Clear temporary variables
    clear opts
    %
    cd("-----");
    
    
    cells = zap;
    [CellStrain_end,CellEllipse] = CellStrainCalc_endpoint(CellEllipse, 76,cells);
    %[CoronaStrain_end,CoronaEllipse] = CellStrainCalc_endpoint(CoronaData, 76,cells);
    
    
    
    G = zeros(time,length(cells));
    GG = zeros(time,length(cells));
    K = zeros(time,length(cells));
    KK = zeros(time,length(cells));
    M = zeros(time,length(cells));
    MM = zeros(time,length(cells));
    g = zeros(time, 1);
    gg = zeros(time, 1);
    k = zeros(time, 1);
    kk = zeros(time, 1);
    m = zeros(time, 1);
    mm = zeros(time, 1);
    
    
    for jj=1:length(cells)
        % g is corona strain in the xx direction.
        % gg is cell strain in the xx direction
        
        % k is corona strain Eyy
        % kk is corona strain in the yy direction
        %cells(jj)
        
        % m is Area strain of corona
        % mm is Area strain of cell
        
        for i=2:time
            %   i
            %collect Exx of that cell's corona
            g(i)=[CoronaStrain_end([CoronaStrain_end.CellID]==cells(jj) & [CoronaStrain_end.time]==i).Exx];
            
            
            %Doing the same as above for the YY direction:
            k(i)=[CoronaStrain_end([CoronaStrain_end.CellID]==cells(jj) & [CoronaStrain_end.time]==i).Eyy];
            
            
            gg(i)=[CellStrain_end([CellStrain_end.CellID]==cells(jj)& [CellStrain_end.time]==i).Exx];
            
            kk(i)=[CellStrain_end([CellStrain_end.CellID]==cells(jj)& [CellStrain_end.time]==i).Eyy];
            
            %AC is area strain stuff
            mm(i)= [CellStrain_end([CellStrain_end.CellID]==cells(jj)& [CellStrain_end.time]==i).EA];
            m(i) = [CoronaStrain_end([CoronaStrain_end.CellID]==cells(jj)& [CoronaStrain_end.time]==i).EA];
            
        end
        
        G(:,jj) = g;
        GG(:,jj) = gg;
        K(:,jj) = k;
        KK(:,jj) = kk;
        M(:,jj) = m;
        MM(:,jj) = mm;
        
    end
    cd(basedir);
    save('wspace.mat');
    
    
    cd(basedir);
    save('wspace_strains.mat');
    save('mm_all.txt', 'mm_all', '-ascii');
    
    
    %populating master file with results, append if there is already something
    %there
    %p = [1, 1/5, 1/70, 0.8, 1.3, 15, 0, 1/10, 50, 1,0, 0.8, 0.4,nrun];
    %q(:,1) = [basedir; basedir; basedir; basedir; basedir];
    q(:,1) = basedir;
    q(:,2) = ps_now(1); %rest
    q(:,3) = ps_now(2); %amp
    q(:,4) = ps_now(3); %slope
    q(:,5) = ps_now(4); %freq
    q(:,6) = ps_now(5);    %pack
    q(:,7) = ps_now(6);    %visc
    q(:,8) = ps_now(7); %rest neighbors
    q(:,9) = ps_now(8); %amp neighbors
    q(:,10) = ps_now(9); %freq neighbors
    q(:,11) = ps_now(10); %phase delay neighbors
    q(:,12) = ps_now(11); %distribution used
    q(:,13) = ps_now(12); % min rest length
    q(:,14) = ps_now(13); % width of rest length distribution
    q(:,18) = notes;
    %q(:,5) = [mm_all(:,1); mm_all(:,2); mm_all(:,3);mm_all(:,4); mm_all(:,5)];
    q(1,19:time+18) = mm_all(:,1)';
    % q(2,6:time+5) = mm_all(:,2)';
    % q(3,6:time+5) = mm_all(:,3)';
    % q(4,6:time+5) = mm_all(:,4)';
    % q(5,6:time+5) = mm_all(:,5)';
    Num = xlsread('--');
    Len = size(Num, 1);
    xlswrite('--', q, 'Sheet1', strcat('A',num2str(Len+1)));
    
    
    
    clearvars -except fnames starttime ps notes
end
endtime = datetime('now');
endtime-starttime
